//setdata调用频繁，考虑用this。data。signMsg
var app = getApp()
Page({
  data:{
    greeting:"早上好！",
    signMsg:'签到',
    userInfo:{},
    isBind:false,
    isSign:false,
    expire:false
  },
  //加载初始化
  onLoad:function(){
    console.log('onLoad')
    this.getLoc()
    //获取用户信息和openid
    var myOpenid
    var that = this
    app.getOpenid(function(openid){
      that.data.openid = openid
      console.log(openid)
    })
    app.getUserInfo(function(userInfo){
      that.data.userInfo = userInfo
    })
    //检查当前时间是否在签到时间内
    var now = new Date()
    if(now.getHours() >= 6 && now.getHours() <= 7){
      this.data.signMsg = '签到'
      this.data.expire = false
    }else{
      this.data.signMsg = '只能在6：00至7：00间签到'
      this.data.expire = true
    }
    //检查绑定，如果未绑定，导航到绑定页面
    this.checkBind(function(res){
      if(res){
        this.data.greeting = '你还没有绑定'
      }
    })
    //检查签到
    this.checkSign(function(res){
      if(res){
        this.data.greeting = '你今天已经签过到啦'
      }else{
        this.data.greeting = '你今天还没有签到'
      }
    })
  },

  //检查绑定
  checkBind:function(cb){
    var openid = this.data.openid
    wx.request({
      url:'https://'+app.webroot+"/checkBind/"+openid,
      header:{
        'content-type':'application/json'
      },
      success:function(res){
        if(res.data.state == 'ok'){
          this.data.isBind = true
          typeof cb == 'function' && cb(true)
        }else{
          this.data.isBind = false
          typeof cb == 'function' && cb(false)
        }
      }
    })
  },
  //检查签到
  checkSign:function(cb){
    var openid = this.data.openid
    wx.request({
      url: 'https://'+app.webroot+'/checkSign/'+openid,
      header:{
        'content-type':'application/json'
      },
      success:function(res){
        if(res.data.state == 'ok'){
          this.data.isBind = true
          typeof cb == 'function' && cb(true)
        }else{
          this.data.isBind = false
          typeof cb == 'function' && cb(false)
        }
      }
    })
  },
  //获取位置信息
  getLoc:function(){
    wx.getLocation({
      success: function(res) {
        console.log(res)
      },
    })
  },
  //签到时触发
  sign:function(){
    if(this.data.isBind && this.data.expire && !this.data.isSign){
      wx.request({
        url: 'https://' + app.webroot + '/sign',
        method:'POST',
        header:{
          'content-type':'application/x-www-form-urlencoded'
        },
        data:Util.json2Form({

        }),
        success:function(res){

        }
      })
    }
  }
})

const Util = require('../../utils/util.js')
